package com.tuling.code.algorithm.loadbalance.simple;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 源地址hash算法
 * @author javaw
 *
 */
public class OrignSourceHash implements LoadBlanceStragety{

	@Override
	public String getServer(String clientIp) {
		
		Map<String,Integer> serverMap = new HashMap<>();
		serverMap.putAll(IpMap.serverWeightMap);
		
		Set<String> keySet = serverMap.keySet();
		ArrayList<String> keyList = new ArrayList<>();
		keyList.addAll(keySet);
		
		int hash = clientIp.hashCode();
		int serverCount = keyList.size();
		int serverPos = Math.abs(hash % serverCount);
		
		String server = null;
		
		server = keyList.get(serverPos);
		
		System.out.println("clientIp = "+ clientIp + " , hash = " + hash + " , serverPos="+serverPos + " , serverIp = "+server);
		
		return server;
	}

}
